<jsp:include page="template-top.jsp" />

<link rel="stylesheet" type="text/css" media="screen" href="stylesheets/selfdefine_tooltip.css">
<link rel="stylesheet" type="text/css" media="screen" href="stylesheets/managepage.css">
<link rel="stylesheet" type="text/css" media="screen" href="stylesheets/redmond/jquery-ui-1.8.16.custom.css" >	
<script type="text/javascript" src="javascripts/selfdefine_tooltip.js"></script>
<script type="text/javascript" src="javascripts/jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript" src="javascripts/jquery.tablesorter.js"></script>

<script src="javascripts/jquery.metadata.js" type="text/javascript"></script>

<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.HashSet" %>
<%@ page import="java.lang.StringBuilder" %>
<%@ page import="edu.cmu.ibill.databeans.PersonalBill" %>
<%@ page import="edu.cmu.ibill.databeans.CategoryDict" %>
<%@ page import="java.text.DecimalFormat" %>

<%
	SimpleDateFormat format = new SimpleDateFormat( "MM/dd/yyyy" );
	DecimalFormat df = new DecimalFormat("###.##");
	CategoryDict[] categorydict = (CategoryDict[])request.getAttribute("categorydict");
%>

<!-- These are bill tables -->
<div id="billtables">
<div class="setting">Bills</div>
<%
if(request.getAttribute("personalbills") != null && ((PersonalBill[])request.getAttribute("personalbills")).length>0){
		PersonalBill[] pBills = (PersonalBill[])request.getAttribute("personalbills");
%>
<table id="personalbilltable" cellspacing="0" cellpadding="6">
<thead>
	<tr>
		<th width="100px">Date</th>
		<th width="100px">Category</th>
		<th width="100px">Amount</th>
	</tr>
</thead>
<tbody>
<%
	
		for (int i=0; i<pBills.length; i++) {
			PersonalBill bill=pBills[i];
%>
	<tr class="entry" title="<%=bill.getDescription()%>" value="<%=bill.getDescription()%>">
	<form id="personalbill<%=bill.getId()%>" name="personalbill<%=bill.getId()%>" method="post" action="removebill.do">
	<input type="hidden" class="deleteid" name="id" value="<%=bill.getId()%>">
		<td class="entry_date"><%=format.format(bill.getDate())%></td>
		<td class="entry_category" cat_index="<%=categorydict[bill.getCategoryId()].getId()%>"><%=categorydict[bill.getCategoryId()].getCategoryName()%></td>
		<td class="entry_amount"><%=df.format(bill.getAmount())%></td>
		<td class="buttons">
			<input class="submitedit"  name="Button" value="Edit" type="submit" style="display:none;">
			<!--<input class="submitdelete"  name="Button" value="Delete" type="submit" style="display:none;">-->
		</td>
	</form>
	</tr>

<%
		}
%>
   </tbody>
</table>
<%
}else{
%>
<p class="note-para">You don't have any personal bills currently, click <a href="javascript:$('#submitaddpersonal').click();">Report personal bill</a> to add personal bills</p>
<%
}
%>
<p/>
<div class="setting">Debts</div>
<!------------------------------------------------------------------>
<script type="text/javascript">
$(document).ready(function() {
	
	$('#personalbilltable').find("tr.entry").hover(
	  function () {
		$(this).find('input.submitedit').show();
		$(this).find('input.submitdelete').show();
	  }, 
	  function () {
		$(this).find('input.submitedit').hide();
		$(this).find('input.submitdelete').hide();
	  }
	);
	$('#personalbilltable').delegate('tbody tr','mouseover mouseleave', function(e) {
		if (e.type == 'mouseover') {
		  $(this).find('td').not('.buttons').addClass("hover");
		}
		else {
		  $(this).find('td').not('.buttons').removeClass("hover");
		}
	});
	
	$('#submitaddpersonal').click(function() {
		$("#cover").show();
		$('#addpersonal').show();
		$('#addpersonal').addClass('visible');
	});
	$('#submitaddshared').click(function() {
		$("#cover").show();
		$('#addshared').show();
		$('#addshared').addClass('visible');
	});
	$('#submitaddloan').click(function() {
		$("#cover").show();
		$('#addloan').show();
		$('#addloan').addClass('visible');
	});
	$('#submitaddpayment').click(function() {
		$("#cover").show();
		$('#addpayment').show();
		$('#addpayment').addClass('visible');
	});
	$('#canceladdpersonalbill').click(function() {
		$('#addpersonal').hide();
		$('#cover').hide();
		$('#addpersonaltable').find('input.text').val("");
		$('#addpersonaltable').find('textarea').val("");
		$('#addpersonaltable').find('select').val("0");
		$('#addpersonal').find('p.error').remove();
		$('#addpersonal').removeClass('visible');
		return false; // prevent submitting the form
	});
	
	$('.submitedit').click(function() {
		$("#cover").show();
		$('#editpersonal').show();
		$('#editpersonal').addClass('visible');
		// fill the edit form with the chosen data
		var $table = $(this).parents('tr');
		$('#updateid').val($table.find('.deleteid').val());
		$('#edit_date').val($table.find('.entry_date').text());
		$('#edit_amount').val($table.find('.entry_amount').text());
		$('#edit_category').val($table.find('.entry_category').attr('cat_index'));
		$('#edit_comment').val($table.attr("value"));

		return false;
	});
	
	$('#canceleditpersonalbill').click(function() {
		$('#editpersonal').hide();
		$('#cover').hide();
		$('#editpersonaltable').find('input.text').val("");
		$('#editpersonaltable').find('textarea').val("");
		$('#editpersonaltable').find('select').val("0");
		$('#editpersonal').find('p.error').remove();
		$('#editpersonal').removeClass('visible');
		return false; // prevent submitting the form
	});
	addloancancel
	$('#addloancancel').click(function() {
		$('#addloan').hide();
		$('#cover').hide();
		$('#addloan').find('input.text').val("");
		$('#addloan').find('textarea').val("");
		$('#addloan').find('p.error').remove();
		$('#addloan').removeClass('visible');
		return false; // prevent submitting the form
	});
	$('#addpaymentcancel').click(function() {
		$('#addpayment').hide();
		$('#cover').hide();
		$('#addpayment').find('input.text').val("");
		$('#addpayment').find('textarea').val("");
		$('#addpayment').find('p.error').remove();
		$('#addpayment').removeClass('visible');
		return false; // prevent submitting the form
	});
	
	$("#personalbilltable").tableSorter({	});
	
	$('#personalbilltable').find('td.entry_amount').addClass("{sorter: 'floating'}");
	
	$('#canceladdsharedbill').click(function() {
		$('#addshared').hide();
		$('#cover').hide();
		$('#addshared').find('input[type=text]').val("");
		$('#addshared').find('textarea').val("");
		$('#addshared').find('select').val("0");
		$('#addshared').find('tr.participant').remove();
		$('#addshared').find('p.error').remove();
		$('#addshared').removeClass('visible');
		clearParticipants();
		return false; // prevent submitting the form
	});
	
	$('#addparticipant').click(function() {
		tryEmail();
		return false; // prevent submitting the form
	});
});

$(function() {
	$( "#date" ).datepicker();
});
$(function() {
	$( "#edit_date" ).datepicker();
	$( "#addshared_date" ).datepicker();
	$( "#addloan_date" ).datepicker();
});
</script>

<script type="text/javascript">
// make sure amount input is a valid number
function checkNumber(e,txt) 
{ 
	var key = window.event ? e.keyCode : e.which; 
	var keychar = String.fromCharCode(key); 
	reg = /\d|\./; 
	var result = reg.test(keychar); 
	if(result) 
	{ 
		if(e.keyCode==46) 
			result=!(txt.value.split('.').length>1); 
		else 
			result=!(txt.value.split('.').length>1&&txt.value.split('.')[1].length>1); 
	} 
	if(!result) 
	{ 
		return false; 
	} 
	else 
	{ 
		return true; 
	} 
} 
</script>

<!-- this is a form to add new personal bills -->
<div id="addpersonal" align="center" style="display:none;"> 
<%
	java.util.List<String> adderrors = (java.util.List) request.getAttribute("addpersonalbillerrors");
	if (adderrors != null && adderrors.size() > 0) {
%>
	<p class="error">
<%
		for (String error : adderrors) {
%>
			<%=error%><br/>
<%
		}
%>
	</p>
<%
	}
%>
<form method="post" action="addbill.do">
		<table id="addpersonaltable" class="personaltable">
			<tr>
				<td class="label"> Date: </td>
				<td><input class="text" type="text" id="date" name="date" value=""/></td>
			</tr>
			<tr>
				<td class="label"> Category: </td>
				<td>
					<select name="category" id="category">
					<option value="0" selected="selected"></option>
					<%
						for(int i=1;i<categorydict.length;i++){
					%>
						<option value="<%=categorydict[i].getId()%>"><%=categorydict[i].getCategoryName()%></option>
					<%
						}
					%>
					</select>
				</td>
			</tr>
			<tr>
				<td class="label"> Amount: </td>
				<td><input class="text" type="text" id="amount" name="amount" value="" onkeypress="return checkNumber(event,this);"/></td>
			</tr>
			<tr>
				<td class="label"> coment: </td>
				<td><textarea id="comment" name="comment"></textarea></td>
			</tr>
			<tr>
				<td colspan="2" align="right">
					<input class="personaltablebutton" type="submit" id="addpersonalbill"  name="Button" value="Add Bill"/>
					<input class="personaltablebutton" type="submit" id="canceladdpersonalbill"  name="Button" value="Cancel"/>
				</td>
			</tr>
		</table>
</form>

	<%
		if(request.getAttribute("addpersonalbillinprocess")!= null){
	%>
	<script type="text/javascript">
		$("#cover").show();
		$('#addpersonal').show();
		$('#addpersonal').addClass('visible');
		$('#date').val("${date}");
		$('#category').val("${category}");
		$('#amount').val("${amount}");
		$('#comment').val("${comment}");
	</script>
	<%
		}
	%>
	
</div>
<!-- end add personal bill -->

<!-- this is a form to edit existing personal bills -->
<div id="editpersonal" align="center" style="display:none;"> 
<%
	java.util.List<String> editerrors = (java.util.List) request.getAttribute("editpersonalbillerrors");
	if (editerrors != null && editerrors.size() > 0) {
%>
	<p class="error">
<%
		for (String error : editerrors) {
%>
			<%=error%><br/>
<%
		}
%>
	</p>
<%
	}
%>
<form method="post" action="updatebill.do">
		<input type="hidden" id="updateid" name="id" value="">
		<table id="editpersonaltable" class="personaltable">
			<tr>
				<td class="label"> Date: </td>
				<td><input class="text" type="text" id="edit_date" name="date" value=""/></td>
			</tr>
			<tr>
				<td class="label"> Category: </td>
				<td>
					<select name="category" id="edit_category">
					<option value="0" selected="selected"></option>
					<%
						for(int i=1;i<categorydict.length;i++){
					%>
						<option value="<%=categorydict[i].getId()%>"><%=categorydict[i].getCategoryName()%></option>
					<%
						}
					%>
					</select>
				</td>
			</tr>
			<tr>
				<td class="label"> Amount: </td>
				<td><input class="text" type="text" id="edit_amount" name="amount" value="" onkeypress="return checkNumber(event,this);"/></td>
			</tr>
			<tr>
				<td class="label"> coment: </td>
				<td><textarea id="edit_comment" name="comment"></textarea></td>
			</tr>
			<tr>
				<td colspan="2" align="right">
					<input class="personaltablebutton" type="submit" id="editpersonalbill"  name="Button" value="Update Bill"/>
					<input class="personaltablebutton" type="submit" id="canceleditpersonalbill"  name="Button" value="Cancel"/>
				</td>
			</tr>
		</table>
</form>

	<%
		if(request.getAttribute("editpersonalbillinprocess")!= null){
	%>
	<script type="text/javascript">
		$("#cover").show();
		$('#editpersonal').show();
		$('#editpersonal').addClass('visible');
		$('#updateid').val("${editid}");
		$('#edit_date').val("${editdate}");
		$('#edit_amount').val("${editamount}");
		$('#edit_category').val("${editcategory}");
		$('#edit_comment').val("${editcomment}");
	</script>
	<%
		}
	%>

</div>
<!-- end edit personal bill -->

<!-- this is a form to add shared bills -->
<div id="addshared" align="center" style="display:none;"> 
<%
	java.util.List<String> addsharederrors = (java.util.List) request.getAttribute("addsharedbillerrors");
	if (addsharederrors != null && addsharederrors.size() > 0) {
%>
	<p class="error">
<%
		for (String error : addsharederrors) {
%>
			<%=error%><br/>
<%
		}
%>
	</p>
<%
	}
%>

<form method="post" action="addsharedbill.do">
		<table id="addsharedtable" class="sharedtable">
			<tr>
				<td class="label"> Date: </td>
				<td><input class="text" type="text" id="addshared_date" name="date" value=""/></td>
			</tr>
			<tr>
				<td class="label"> Category: </td>
				<td>
					<select name="category" id="addshared_category">
					<option value="0" selected="selected"></option>
					<%
						for(int i=1;i<categorydict.length;i++){
					%>
						<option value="<%=categorydict[i].getId()%>"><%=categorydict[i].getCategoryName()%></option>
					<%
						}
					%>
					</select>
				</td>
			</tr>
			<tr>
				<td class="label"> Amount: </td>
				<td><input class="text" type="text" id="addshared_amount" name="amount" value="" onkeypress="return checkNumber(event,this);"/></td>
			</tr>
			<tr>
				<td class="label"> coment: </td>
				<td><textarea id="addshared_comment" name="comment"></textarea></td>
			</tr>
			<tr>
				<td class="label" colspan="2"> Participants: </td>
			</tr>
			<tr id="addsharedparticipant">
				<td colspan="2">
					<input type="text" id="addshared_participant" name="participant" value="" />
					<input class="sharedtablebutton" type="submit" id="addparticipant"  name="Button" value="Add"/>
				</td>
			</tr>
			<tr id="addsharedbillbuttons">
				<td align="left">
					<input class="sharedtablebutton" type="submit" id="evenamount"  name="Button" value="Even Amount"/>
				</td>
				<td align="right">
					<input class="sharedtablebutton" type="submit" id="addsharedbill"  name="Button" value="Report Bill"/>
					<input class="sharedtablebutton" type="submit" id="canceladdsharedbill"  name="Button" value="Cancel"/>
				</td>
			</tr>
		</table>
</form>
</div>
<!-- end add shared bill -->

<!-- a warning window for the page -->
<div id="pagewarning" align="center" style="display:none;">
<p id="pagewarningcontent"></p>
<input class="pagewarningbutton" type="submit" id="pagewarningok"  name="Button" value="Ok"/> 
</div>
<script type="text/javascript">
// shows the warning window
function showWarning(warning){
	$('#pagewarningcontent').text(warning);
	$("#cover").show();
	$('#pagewarning').show();
}
</script>
<!-- end warning window -->

<!-- -->
<script type="text/javascript">
var participants={};
var parcount=0;

function clearParticipants(){
	participants={};
	parcount=0;
}

function tryEmail(){
	if($('#addshared_participant').val()==""){
		// if input is empty, ignore
	}else{
		var url = "addshareduser.do?email="+$('#addshared_participant').val();
		sendRequest(url);
	}
}    
var XMLHttpReq = false;
//create XMLHttpRequest object       
function createXMLHttpRequest() {
    if(window.XMLHttpRequest) { //Mozilla browser
        XMLHttpReq = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) { // IE
        try {
            XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }
}
//send request
function sendRequest(url) {
    createXMLHttpRequest();
    XMLHttpReq.open("GET", url, true);
    XMLHttpReq.onreadystatechange = processResponse;
    XMLHttpReq.send(null); 
}
//process response
function processResponse() {
    if (XMLHttpReq.readyState == 4) { 
        if (XMLHttpReq.status == 200) { 
            var result = XMLHttpReq.responseText;
			// process request
			var pId = result.substring(0,result.indexOf(';'));
			var pName= result.substring(result.indexOf(';')+1);
			if(pId=="-1"){
				// user not exist;
				showWarning("User does not exist");
			}else{
				addPar(pId,pName,"0");
			}
        } else { 
            showWarning("Ooops, unkown exception");
        }
    }
}

function addPar(pId,pName,cash){
	if(!participants[pId]){
		participants[pId]=true;
		parcount++;
		$('#addshared_participant').val("");
		$('#addsharedbillbuttons').before(
		"<tr class=\"participant\">"+
		"<input class=\"hidid\" type=\"hidden\" name=\"user"+parcount+"\" value=\""+pId+"\"/>"+
		"<input class=\"hidname\" type=\"hidden\" name=\"uname"+parcount+"\" value=\""+pName+"\"/>"+
		"<td width=\"95px\"><b>"+
		pName+
		"</b></td><td>"+
		"  amount:"+
		"<input type=\"text\" name=\"amount"+parcount+"\" value=\""+cash+"\" onkeypress=\"return checkNumber(event,this);\"/>"+
		"<input type=\"submit\" class=\"removepar\" value=\"Remove\" />"+
		"</td></tr>");
	}
}

$(document).ready(function() {
	$('#addsharedtable').find('.removepar').click(function() {
		var $table = $(this).parents('tr');
		$table.remove();
		clearParticipants();
		$('tr.participant').each(function(index) {
			$(this).find('.hidid').attr("name","user"+(index+1));
			$(this).find('.hidname').attr("name","uname"+(index+1));
			$(this).find('[type=text]').attr("name","amount"+(index+1));
		});
  
		return false; // prevent submitting the form
	});
	$('#addsharedbill').click(function() {
		var total = parseFloat($('#addshared_amount').val());
		total=Math.round(total*100);
		$('tr.participant').each(function(index) {
			var t = parseFloat($(this).find('[type=text]').val());
			total = total - Math.round(t*100);
		});
		if(total!=0){
			showWarning("Sum of the amounts of participants should be equal to the total amount");
			return false;
		}else{
			return true;
		}
	});
	$('#evenamount').click(function() {
		if($('#addshared_amount').val()==""){
			showWarning("Put in Amount first");
		}else{
			var len = $('.participant').length;
			if(len == 0){
			}else{
				var total = parseFloat($('#addshared_amount').val());
				var ev = (Math.floor(total*100/len))/100;
				var ams = new Array();
				for(i=0;i<len;i++){
					ams[i] = ev;
					total = total-ev;
				}
				for(i=0;i<len;i++){
					if(Math.round(total*100)>=1){
						ams[i]=ams[i]+0.01;
						total=total-0.01;
					}else{
						break;
					}
				}
				$('tr.participant').each(function(index) {
					$(this).find('[type=text]').val((Math.round(ams[index]*100))/100);
				});
			}
		}
		return false;
	});
	$('#pagewarningok').click(function() {
		$(pagewarning).hide();
		if($('#addpersonal').hasClass('visible') || $('#addshared').hasClass('visible') || $('#editpersonal').hasClass('visible') || $('#addloan').hasClass('visible') || $('#addpayment').hasClass('visible')){}else{
		$('#cover').hide();
		}
	});
	
});
</script>

	<%
		if(request.getAttribute("addsharedbillinprocess")!= null){
	%>
	<script type="text/javascript">
		$("#cover").show();
		$('#addshared').show();
		$('#addshared').addClass('visible');
		$('#addshared_date').val("${addshared_date}");
		$('#addshared_amount').val("${addshared_amount}");
		$('#addshared_category').val("${addshared_category}");
		$('#addshared_comment').val("${addshared_comment}");
		clearParticipants();
		<%
			int i=1;
			while(true){
				if(request.getAttribute("addshared_user"+i)!= null){
				String u=(String)request.getAttribute("addshared_user"+i);
				String n=(String)request.getAttribute("addshared_uname"+i);
				String a=(String)request.getAttribute("addshared_amount"+i);
		%>
			addPar("<%=u%>","<%=n%>","<%=a%>");
		<%
				i++;
				}else{
					break;
				}
			}
		%>
	</script>
	<%
		}
	%>
<!-- -->

<!-- this is a form to add loan -->
<div id="addloan" align="center" style="display:none;"> 
<%
	java.util.List<String> addloanerrors = (java.util.List) request.getAttribute("addloanerrors");
	if (addloanerrors != null && addloanerrors.size() > 0) {
%>
	<p class="error">
<%
		for (String error : addloanerrors) {
%>
			<%=error%><br/>
<%
		}
%>
	</p>
<%
	}
%>
<form method="post" action="adddebt.do">
		<table id="addloantable" class="personaltable">
			<tr>
				<td class="label"> Loaner: </td>
				<td><input class="text" type="text" id="addloan_email" name="email" value=""/></td>
			</tr>
			<tr>
				<td class="label"> Date: </td>
				<td><input class="text" type="text" id="addloan_date" name="date" value=""/></td>
			</tr>
			<tr>
				<td class="label"> Amount: </td>
				<td><input class="text" type="text" id="addloan_amount" name="amount" value="" onkeypress="return checkNumber(event,this);"/></td>
			</tr>
			<tr>
				<td class="label"> coment: </td>
				<td><textarea id="addloan_comment" name="comment"></textarea></td>
			</tr>
			<tr>
				<td colspan="2" align="right">
					<input class="personaltablebutton" type="submit" id="addloanok"  name="Button" value="Report Loan"/>
					<input class="personaltablebutton" type="submit" id="addloancancel"  name="Button" value="Cancel"/>
				</td>
			</tr>
		</table>
</form>

	<%
		if(request.getAttribute("addloaninprocess")!= null){
	%>
	<script type="text/javascript">
		$("#cover").show();
		$('#addloan').show();
		$('#addloan').addClass('visible');
		$('#addloan_date').val("${date}");
		$('#addloan_email').val("${email}");
		$('#addloan_amount').val("${amount}");
		$('#addloan_comment').val("${comment}");
	</script>
	<%
		}
	%>
	
</div>
<!-- end add loan -->

<!-- this is a form to add payment -->
<div id="addpayment" align="center" style="display:none;"> 
<%
	java.util.List<String> addpaymenterrors = (java.util.List) request.getAttribute("addpaymenterrors");
	if (addpaymenterrors != null && addpaymenterrors.size() > 0) {
%>
	<p class="error">
<%
		for (String error : addpaymenterrors) {
%>
			<%=error%><br/>
<%
		}
%>
	</p>
<%
	}
%>
<form method="post" action="addpayment.do">
		<table id="addpaymenttable" class="personaltable">
			<tr>
				<td class="label"> Receiver: </td>
				<td><input class="text" type="text" id="addpayment_email" name="email" value=""/></td>
			</tr>
			<tr>
				<td class="label"> Date: </td>
				<td><input class="text" type="text" id="addpayment_date" name="date" value=""/></td>
			</tr>
			<tr>
				<td class="label"> Amount: </td>
				<td><input class="text" type="text" id="addpayment_amount" name="amount" value="" onkeypress="return checkNumber(event,this);"/></td>
			</tr>
			<tr>
				<td class="label"> coment: </td>
				<td><textarea id="addpayment_comment" name="comment"></textarea></td>
			</tr>
			<tr>
				<td colspan="2" align="right">
					<input class="personaltablebutton" type="submit" id="addpaymentok"  name="Button" value="Report Loan"/>
					<input class="personaltablebutton" type="submit" id="addpaymentcancel"  name="Button" value="Cancel"/>
				</td>
			</tr>
		</table>
</form>

	<%
		if(request.getAttribute("addpaymentinprocess")!= null){
	%>
	<script type="text/javascript">
		$("#cover").show();
		$('#addpayment').show();
		$('#addpayment').addClass('visible');
		$('#addpayment_date').val("${date}");
		$('#addpayment_email').val("${email}");
		$('#addpayment_amount').val("${amount}");
		$('#addpayment_comment').val("${comment}");
	</script>
	<%
		}
	%>
	
</div>
<!-- end payment -->

</div>

<div id="divlinks"> 
		<p/>
		<a id="submitaddpersonal" class="linkbutton">Report personal bill </a>
		<p/>
		<a id="submitaddshared" class="linkbutton">Report shared bill </a>
		<p/>
		<a id="submitaddloan" class="linkbutton">Report loan </a>
		<p/>
		<a id="submitaddpayment" class="linkbutton">Report payment </a>
</div>	

<div id="cover"/>

<jsp:include page="template-bottom.jsp" />